//
// Created by 123 on 2024/4/1.
//
/**
 * 直接插入排序
 *      默认前面有序，诸逐个拿后面的无序序列和
 *  前面的有序数列，然后决定插入位置
 *
 *  O（n^2)
 */
#include <iostream>

using namespace std;

#define MaxSize 100

typedef struct Array {
    int data[MaxSize];
    int length;
} Array, *Arr;

Array *initArray(int arr[], int len);

void direct_insert_sort(Arr &arr);


int main() {
    int a[10]{49, 38, 65, 97, 76, 13, 27, 49, 55, 4};
    Arr arr = initArray(a, 10);
    direct_insert_sort(arr);
    for (int i = 0; i < arr->length; ++i) {
        cout << arr->data[i] << "    ";
    }
}

void direct_insert_sort(Arr &arr) {
//    下标从 1 开始，默认0有序
    for (int i = 1; i < arr->length; ++i) {
        if (arr->data[i] < arr->data[i-1]) {
            int data = arr->data[i];
            int j = i;
            for (j; j > 0 && data< arr->data[j-1]; j--) {
                arr->data[j] = arr->data[j-1];
            }
            arr->data[j] = data;
        }
    }
}


Array *initArray(int arr[], int len) {
    Arr array = (Array *) malloc(sizeof(Array));
    for (int i = 0; i < len; ++i) {
        array->data[i] = arr[i];
    }
    array->length = len;
    return array;
}